package zhishu.iceyyy.com.bxq_2500.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import zhishu.iceyyy.com.bxq_2500.R;
import zhishu.iceyyy.com.bxq_2500.api.API;
import zhishu.iceyyy.com.bxq_2500.api.Okhttp;
import zhishu.iceyyy.com.bxq_2500.base.BaseApplication;
import zhishu.iceyyy.com.bxq_2500.bean.Shareurl;
import zhishu.iceyyy.com.bxq_2500.utils.DeviceUtil;
import zhishu.iceyyy.com.bxq_2500.utils.JSONUtils;
import zhishu.iceyyy.com.bxq_2500.utils.QRCode;
import zhishu.iceyyy.com.bxq_2500.utils.SpfUtils;


/**
 * 主
 */
public class Share_Fragment extends Fragment {


    View view;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.textView7)
    TextView textView7;
    @BindView(R.id.tv_uuid)
    TextView tvUuid;

    @BindView(R.id.imageView3)
    ImageView imageView3;

    @BindView(R.id.textView13)
    TextView textView13;
    @BindView(R.id.button2)
    TextView button2;
    Bitmap qrCodeWithLogo5;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = View.inflate(getActivity(), R.layout.fragment_share, null);
            ButterKnife.bind(this, view);
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(), "复制成功，请分享给您的好友！", Toast.LENGTH_SHORT).show();
                }
            });
            tvUuid.setText(DeviceUtil.getDeviceId(BaseApplication.getInstance()));
            API.shareurl(new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String st) {
                    Log.e("111", "xx" + st);
                    SpfUtils.put(getActivity(), "shareurl", st);
                    Shareurl shareurl = JSONUtils.parseJSON(st, Shareurl.class);
                    String code = shareurl.getCode();
                    if (code.equals("200")) {
                        Shareurl.DataBean data = shareurl.getData();
                        String shareurl1 = data.getShareurl();
                        qrCodeWithLogo5 = QRCode.createQRCodeWithLogo5(shareurl1, 600, drawableToBitmap(getResources().getDrawable(R.drawable.ic)));
                        imageView3.setImageBitmap(qrCodeWithLogo5);
                        textView13.setText("官网" + shareurl1);
                    } else {
                        Toast.makeText(getActivity(), shareurl.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onFalia(int code, String errst) {
                    Log.e("111", "xx" + errst);

                    String shareurls = (String) SpfUtils.get(getActivity(), "shareurl", "");
                    if (TextUtils.isEmpty(shareurls)) {
                        Toast.makeText(getActivity(), "网络错误," + errst, Toast.LENGTH_SHORT).show();
                    } else {
                        Shareurl shareurl = JSONUtils.parseJSON(shareurls, Shareurl.class);
                        String codes = shareurl.getCode();
                        if (codes.equals("200")) {
                            Shareurl.DataBean data = shareurl.getData();
                            String shareurl1 = data.getShareurl();
                            qrCodeWithLogo5 = QRCode.createQRCodeWithLogo5(shareurl1, 600, drawableToBitmap(getResources().getDrawable(R.drawable.ic)));
                            imageView3.setImageBitmap(qrCodeWithLogo5);
                            textView13.setText("官网" + shareurl1);
                        } else {
                            Toast.makeText(getActivity(), shareurl.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });


        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }


        return view;
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();


    }

    private static final String SD_PATH = "/sdcard/dskqxt/pic/";
    private static final String IN_PATH = "/dskqxt/pic/";

    /**
     * 随机生产文件名
     *
     * @return
     */
    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }


    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }


    @OnClick({R.id.bt_verify, R.id.bt_yaoqing})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_verify:
                if (qrCodeWithLogo5 != null) {
                    String s = saveBitmap(getActivity(), qrCodeWithLogo5);
                    sendVideo(s);
                    Toast.makeText(getActivity(), "保存成功！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "保存失敗！", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.bt_yaoqing:
                break;
        }
    }

    MediaScannerConnection msc = null;
    ProgressDialog progressDialog = null;

    public void sendVideo(final String localPath) {
        if (TextUtils.isEmpty(localPath)) {
            return;
        }
        if (msc == null)
            msc = new MediaScannerConnection(getActivity(),
                    new MediaScannerConnection.MediaScannerConnectionClient() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            msc.disconnect();
                            msc = null;
                            progressDialog.dismiss();
                            Log.e("path", "localPaht:" + localPath
                                    + "&&&&&&path:" + path + "&&&&&&&&&&uri:"
                                    + uri.getPath());


                        }

                        @Override
                        public void onMediaScannerConnected() {
                            msc.scanFile(localPath, "video/*");
                        }
                    });

        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("保存中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
        msc.connect();

    }
}

